import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef, EventEmitter } from '@angular/core'; 
import { XmMessageItemData, XmMessgaeOptions } from './types';

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MessageComponent implements OnInit {
  readonly defaultConfig: Required<XmMessgaeOptions> = {
    type: 'info',
    duration: 3000,
    showClose: false,
    pauseOnHover: false,
    maxStack:5,
    animate:true
  };
  messages: XmMessageItemData[] = [];
  empty = new EventEmitter();
  constructor(private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {}
  
  createMessage(message: XmMessageItemData): void {
    message.options = { ...this.defaultConfig, ...message.options };
    if (message.options.maxStack > 0 && this.messages.length >= message.options.maxStack) {
      this.removeMessage(this.messages[0].messageId);
    }
    this.messages.push(message);
    this.cdr.markForCheck();
  }
  removeMessage(messageId: string) {
    const targetIndex = this.messages.findIndex(
      (item) => item.messageId == messageId
    );
    if (targetIndex > -1) {
      this.messages[targetIndex].onClose.next();
      this.messages[targetIndex].onClose.complete();
      this.messages.splice(targetIndex, 1);
      this.cdr.markForCheck();
    }
    if (this.messages.length === 0) {
      this.empty.emit();
    }
  }
}
